import axios from 'axios';
// import env from '../../build/env';
import packjson from '../../package.json';

let util = {

};
util.pjArgu = obj => {
        let str;
        for (let key in obj) {
            str += `&${key}=${obj[key]}`
        }
        return str
    },
    util.amount = th => {
        let regStrs = [
            ['^0(\\d+)$', '$1'], //禁止录入整数部分两位以上，但首位为0 
            ['^[1-9](\\d{6,})$', '$1'],
            ['[^\\d\\.]+$', ''], //禁止录入任何非数字和点  
            ['[^\\d\.]+', ''],
            ['\\.(\\d?)\\.+', '.$1'], //禁止录入两个以上的点  
            ['^(\\d+\\.\\d{2}).+', '$1'], //禁止录入小数点后两位以上  
            ['^\d+(\.\d+)?$', '']
        ];
        for (let i = 0; i < regStrs.length; i++) {
            let reg = new RegExp(regStrs[i][0]);
            th = th.replace(reg, regStrs[i][1]);

        }
        return th
    }
util.bpower = (vm, obj) => {
    let btnPower = [];
    if (vm.$store.state.user.btnPower.length > 0) {
        btnPower = vm.$store.state.user.btnPower;
    } else {
        btnPower = JSON.parse(localStorage.btnPower);
    }
    let keyArr = Object.keys(obj);
    let nObj = {};
    keyArr.map(item => {
        if (btnPower.includes(item)) {
            nObj[item] = true;
        } else {
            nObj[item] = false;
        }
    })
    return nObj
}
util.validateIdCard = idCard => {
    const regIdCard = /^(^[1-9]\d{7}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{3}$)|(^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])((\d{4})|\d{3}[Xx])$)$/;
    if (regIdCard.test(idCard)) {
        if (idCard.length == 18) {
            const idCardWi = new Array(7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2);
            const idCardY = new Array(1, 0, 10, 9, 8, 7, 6, 5, 4, 3, 2);
            let idCardWiSum = 0;
            for (let i = 0; i < 17; i++) {
                idCardWiSum += idCard.substring(i, i + 1) * idCardWi[i];
            }
            let idCardMod = idCardWiSum % 11; //计算出校验码所在数组的位置  
            let idCardLast = idCard.substring(17); //得到最后一位身份证号码 
            if (idCardMod == 2) {
                if (idCardLast == "X" || idCardLast == "x") {
                    return true
                } else {
                    return false
                }
            } else {
                if (idCardLast == idCardY[idCardMod]) {
                    return true
                } else {
                    return false
                }
            }
        } else {
            return true
        }
    } else {
        return false
    }
}
util.TreeFormat2 = (arr, uuid) => {
    let nArr = arr.map(item => {
        if (item.uuid == uuid) {
            item.selected = true;
        }
        item.title = item.name;
        if (!!item.children && item.children.length > 0) {
            item.children = util.TreeFormat(item.children, uuid)
        }
        return item
    })
    return nArr
}
util.TreeFormat = (arr, uuid) => {
    let nArr = arr.map(item => {
        if (item.uuid == uuid) {
            item.selected = true;
        }
        item.title = item.name;
        item.disabled = item.canChoose == 'false';
        if (!!item.children && item.children.length > 0) {
            item.children = util.TreeFormat(item.children, uuid)
        }
        return item
    })
    return nArr
}
util.time1 = (time) => {
    let date = new Date(time);
    let Y = date.getFullYear() + '-'
    let M = ('0' + (date.getMonth() + 1)).slice(-2) + '-'
    let D = ('0' + date.getDate()).slice(-2) + ' '
    let h = ('0' + date.getHours()).slice(-2) + ':'
    let m = ('0' + date.getMinutes()).slice(-2)
    return Y + M + D + h + m
}
util.isCustomer = (vm) => {
    if (!!vm.$store.state.user.info.user_type) {
        vm.user_type = vm.$store.state.user.info.user_type;
        vm.userUuid = vm.$store.state.user.info.inst_uuid;
    } else {
        vm.user_type = JSON.parse(localStorage.userInfo).user_type;
        vm.userUuid = JSON.parse(localStorage.userInfo).inst_uuid;
    }
    if (vm.user_type === '01' && !!vm.columns) {
        vm.columns.splice(vm.columns.indexOf(item => {
            item.title == "客户" || item.title == "所属客户"
        }), 1)
    }
    if (vm.user_type === '02' && !!vm.columns) {
        vm.columns.splice(vm.columns.indexOf(item => {
            item.title == "服务商" || item.title == "所属服务商"
        }), 1)
    }
}
util.changeAreaKey = (area) => {
    let newArea = area.map(item => {
        let a = {};
        a.label = item.name;
        a.value = item.name;
        if (!!item.children && item.children.length > 0) {
            a.children = util.changeAreaKey(item.children);

        }
        return a

    })
    return newArea
}
util.jiangw = arr => {

    let narr = [];
    // console.log(arr)
    for (let i = 0; i < arr.length; i++) {

        let a = {};

        a.inst_uuid = arr[i].uuid;
        a.inst_name = arr[i].name;

        narr = [...narr, a];
        // console.log({ narr })
        // if (arr[i].children.length > 0) {

        //     let barr = util.jiangw(arr[i].children);
        //     console.log({ barr })
        //     narr = [...narr, ...barr];

        // }
    }
    return narr
}
util.tree = (arr) => {
    let nArr = arr.map(item => {
        let a = item;
        a.title = item.name;
        a.value = item.uuid;
        a.checked = false;
        if (item.canChoose == 'false') {
            a.disabled = true;
        }
        if (item.children.length > 0) {
            a.children = util.tree(item.children);
        }
        return a
    })
    return nArr
}
util.arrcheck = (arr1, arr2) => {
    let newArr = arr1.filter(item => {
        let index;
        for (let i = 0, l = arr2.length; i < l; i++) {
            if (arr2[i].name === item.title) {
                index = i;
            }
        }
        if (index > -1 && item.title === "状态总览") {
            return item
        }
        if (index > -1 && !!arr2[index].child) {
            item.children = util.arrcheck(item.children, arr2[index].child);
            return item
        } else if (index > -1) {
            return item
        }
    })
    return newArr
}
util.initMap = (id, lon, lat) => {
    let map = new BMap.Map(id);
    map.enableScrollWheelZoom(true);
    let point = new BMap.Point(lon, lat);
    map.centerAndZoom(point, 18);
    let marker = new BMap.Marker(point); // 创建标注
    map.addOverlay(marker); // 将标注添加到地图中
    marker.setAnimation(BMAP_ANIMATION_BOUNCE); //跳动的动画
    let label = new BMap.Label(`${lon}，${lat}`, { offset: new BMap.Size(20, -10) });
    marker.setLabel(label);
}
util.title = function(title) {
    title = title || '点点维';
    window.document.title = title;
};

// const ajaxUrl = env === 'development'
//     ? 'http://127.0.0.1:8888'
//     : env === 'production'
//         ? 'https://www.url.com'
//         : 'https://debug.url.com';

// util.ajax = axios.create({
//     baseURL: ajaxUrl,
//     timeout: 30000
// });

util.inOf = function(arr, targetArr) {
    let res = true;
    arr.forEach(item => {
        if (targetArr.indexOf(item) < 0) {
            res = false;
        }
    });
    return res;
};

util.oneOf = function(ele, targetArr) {
    if (targetArr.indexOf(ele) >= 0) {
        return true;
    } else {
        return false;
    }
};

util.showThisRoute = function(itAccess, currentAccess) {
    if (typeof itAccess === 'object' && Array.isArray(itAccess)) {
        return util.oneOf(currentAccess, itAccess);
    } else {
        return itAccess === currentAccess;
    }
};

util.getRouterObjByName = function(routers, name) {
    if (!name || !routers || !routers.length) {
        return null;
    }
    // debugger;
    let routerObj = null;
    for (let item of routers) {
        if (item.name === name) {
            return item;
        }
        routerObj = util.getRouterObjByName(item.children, name);
        if (routerObj) {
            return routerObj;
        }
    }
    return null;
};

util.handleTitle = function(vm, item) {
    if (typeof item.title === 'object') {
        return vm.$t(item.title.i18n);
    } else {
        return item.title;
    }
};

util.setCurrentPath = function(vm, name) {
    let title = '';
    let isOtherRouter = false;
    if (name === "config") {
        name = 'cusmg'
    }
    //console.log(vm.$store.state.app.newMenuRouter)
    vm.$store.state.app.newMenuRouter.forEach(item => {
        //console.log(1)
        if (item.children.length === 1) {
            if (item.children[0].name === name) {
                title = util.handleTitle(vm, item);
                if (item.name === 'otherRouter') {
                    isOtherRouter = true;
                }
            }
        } else {
            item.children.forEach(child => {

                if (child.name === name) {
                    title = util.handleTitle(vm, child);
                    if (item.name === 'otherRouter') {
                        isOtherRouter = true;
                    }
                }
            });
        }
    });
    let currentPathArr = [];
    if (name === 'home_index') {
        currentPathArr = [{
            title: '状态总览',
            path: '',
            name: 'home_index'
        }];
        // currentPathArr = [{
        //     title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.newMenuRouter, 'home_index')),
        //     path: '',
        //     name: 'home_index'
        // }];
    } else if ((name.indexOf('_index') >= 0 || isOtherRouter) && name !== 'home_index') {
        // currentPathArr = [{
        //         title: util.handleTitle(vm, util.getRouterObjByName(vm.$store.state.app.newMenuRouter, 'home_index')),
        //         path: '/index/home',
        //         name: 'home_index'
        //     },
        //     {
        //         title: title,
        //         path: '',
        //         name: name
        //     }
        // ];
        currentPathArr = [{
                title: '状态总览',
                path: '/index/home',
                name: 'home_index'
            },
            {
                title: title,
                path: '',
                name: name
            }
        ];
    } else {
        let currentPathObj = vm.$store.state.app.newMenuRouter.filter(item => {
            // if (item.children.length <= 1 && item.name == 'otherRouter') {

            //     return item.children[0].name === name;
            // } else {
            let i = 0;
            let childArr = item.children;
            let len = childArr.length;

            while (i < len) {
                if (childArr[i].name === name) {
                    return true;
                } else if (childArr[i].children) {
                    for (let j = 0; j < childArr[i].children.length; j++) {
                        if (childArr[i].children[j].name === name) {
                            return true
                        }
                    }
                }
                i++;
            }

            return false;
            //}
        })[0];
        //console.log({ currentPathObj })
        // if (currentPathObj.children.length <= 1 && currentPathObj.name === 'home') {
        //     currentPathArr = [{
        //         title: '状态总览',
        //         path: '',
        //         name: 'home_index'
        //     }];
        // } else if (currentPathObj.children.length <= 1 && currentPathObj.name !== 'home') {
        //     currentPathArr = [{
        //             title: '状态总览',
        //             path: '/index/home',
        //             name: 'home_index'
        //         },
        //         {
        //             title: currentPathObj.title,
        //             path: '',
        //             name: name
        //         }
        //     ];
        // } else {
        let childObj = currentPathObj.children.filter((child) => {
            return child.name === name;
        })[0];
        if (childObj) {
            currentPathArr = [
                // {
                //     title: '状态总览',
                //     path: '/index/home',
                //     name: 'home_index'
                // },
                {
                    title: currentPathObj.title,
                    path: '',
                    name: currentPathObj.name
                },
                {
                    title: childObj.title,
                    path: currentPathObj.path + '/' + childObj.path,
                    name: name
                }
            ];
        } else {

            let thirdChildObj = currentPathObj.children.filter((child) => {
                if (child.children) {
                    return child
                }
            })[0];
            let ntChildObj = thirdChildObj.children.filter((child) => {
                return child.name === name;
            })[0];
            currentPathArr = [
                // {
                //     title: '状态总览',
                //     path: '/index/home',
                //     name: 'home_index'
                // },
                {
                    title: currentPathObj.title,
                    path: '',
                    name: currentPathObj.name
                },
                {
                    title: thirdChildObj.title,
                    path: '',
                    name: thirdChildObj.name
                },
                {
                    title: ntChildObj.title,
                    path: currentPathObj.path + '/' + ntChildObj.path,
                    name: name
                }
            ]
        }

        // }
    }
    vm.$store.commit('setCurrentPath', currentPathArr);

    return currentPathArr;
};

util.openNewPage = function(vm, name, argu, query) {
    let pageOpenedList = vm.$store.state.app.pageOpenedList;
    let openedPageLen = pageOpenedList.length;
    let i = 0;
    let tagHasOpened = false;
    while (i < openedPageLen) {
        if (name === pageOpenedList[i].name) { // 页面已经打开
            vm.$store.commit('pageOpenedList', {
                index: i,
                argu: argu,
                query: query
            });
            tagHasOpened = true;
            break;
        }
        i++;
    }
    if (!tagHasOpened) {
        let tag = vm.$store.state.app.tagsList.filter((item) => {
            if (item.children) {
                return name === item.children[0].name;
            } else {
                return name === item.name;
            }
        });
        tag = tag[0];
        if (tag) {
            tag = tag.children ? tag.children[0] : tag;
            if (argu) {
                tag.argu = argu;
            }
            if (query) {
                tag.query = query;
            }
            vm.$store.commit('increateTag', tag);
        }
    }
    vm.$store.commit('setCurrentPageName', name);
};

util.toDefaultPage = function(routers, name, route, next) {
    let len = routers.length;
    let i = 0;
    let notHandle = true;
    while (i < len) {
        if (routers[i].name === name && routers[i].children && routers[i].redirect === undefined) {
            route.replace({
                name: routers[i].children[0].name
            });
            notHandle = false;
            //next();
            break;
        }
        i++;
    }
    if (notHandle) {
        next();
    }
};

util.fullscreenEvent = function(vm) {
    vm.$store.commit('initCachepage');
    // 权限菜单过滤相关
    vm.$store.commit('updateMenulist');
    // 全屏相关
};



// util.onWheel = function (ele, callback) {
//     ele.addEventListener('mousewheel', function (e) {
//         callback(e, e.wheelDelta);
//     });
//     ele.addEventListener('DOMMouseScroll', function (e) {
//         callback(e, e.detail * 40);
//     });
// };

// util.offWheel = function (ele, callback) {
//     ele.removeEventListener('mousewheel', callback)
// }

export default util;